<template>
	<view class="root">
		<uni-calendar ref="calendar" :insert="false" @confirm="confirm" :startDate="startDate" :endDate="endDate" :date="date" />
		<u-action-sheet :list="list" v-model="show" :tips="tips" @click="evaluateTypeClick"></u-action-sheet>
		<scroll-view class="contet" scroll-y="true">
			<view class="children-ready-item">
				<text class="children-title">一、宝宝信息</text>

				<view v-if="assess===0" class="children-info-view">
					<view class="children-info-view-left">
						姓名:<input v-model="name" class="children-info-input" :placeholder-style="placeholderStyle" />
					</view>
					<view class="children-info-view-right">
						生日:<view class="children-info-input" @click="open">{{birthday}}</view>
					</view>
				</view>

				<view class="children-info-view">
					<view class="children-info-view-left">
						身高:<input v-model="height" class="children-info-input" placeholder="CM" :placeholder-style="placeholderStyle"
						 type="number" @input="onlyNumberHeight" />
					</view>
					<view class="children-info-view-right">
						体重:<input v-model="weight" class="children-info-input" placeholder="KG" :placeholder-style="placeholderStyle"
						 type="digit" @input="onlyNumber" />
					</view>
				</view>
				<view v-if="assess===0" class="children-info-view">
					<view>性别:</view>
					<radio-group class="children-sex" @change="radioChange">
						<label>
							<radio :color="color" class="children-sex-radio" value="1">男</radio>
						</label>
						<label>
							<radio :color="color" class="children-sex-radio" value="0">女</radio>
						</label>
					</radio-group>
				</view>
				<view v-if="parentPhone===''||assess===0" class="children-info-view">
					<view>电话:</view>
					<view class="children-info-input" style="flex-grow: 1;">
						<input v-model="phone" maxlength="11" type="number" style="flex-grow: 1;margin-right: 10rpx;" placeholder="输入家长手机号"
						 :placeholder-style="placeholderStyle" />
						<view style="width: 2rpx;height: 60rpx; background-color: rgba(153, 153, 153, 1);"></view>
						<picker @change="bindPickerChange" :value="index" :range="relationship">
							<view class="relationship-view">
								<text style="margin-left: 18rpx;flex-grow: 1;text-align: center;margin-bottom: 5rpx;" :class="index != -1 ?'relationship-style':''">{{index!=-1?relationship[index]:'选择关系'}}</text>
								<view class="relationship-dropdown"></view>
							</view>
						</picker>
					</view>
				</view>
				<view class="children-info-view">
					<view>
						<view>同时开展交流互动警示行为测评</view>
						<view style="font-size: 20rpx;color: #666666;">
							(宝宝在情绪不稳定，或者不配合时请关闭)
						</view>
					</view>
					<switch style="margin-left: 20rpx; transform:scale(0.7)" :checked="false" :color="color" @change="checkChange" />
				</view>
			</view>

			<view class="children-ready-item">
				<text class="children-title">二、测评须知</text>
				<text v-if="appId === 'wx098b4aa58f613e7b' || appId === 'wxfcbfea348616744b'" class="ready-hint">
					1. 把测评使用的道具准备充分。\n2. 准备一间安静的活动室。\n3. 每个宝宝单独测评。\n4. 测评前照护者协助带孩子。\n5. 测评结束后的宝宝由照护者带回活动室。\n6.向家长解释要恰当，注意技巧，尤其对发育落后的宝宝更要慎重。
				</text>
				<text v-else class="ready-hint">
					1. 把测评使用的道具准备充分。\n2. 准备一间安静的教室。\n3. 每个宝宝单独测评。\n4. 测评前生活老师协助带孩子。\n5. 测评结束后的宝宝由生活老师带回大教室。\n6.向家长解释要恰当，注意技巧，尤其对发育落后的宝宝更要慎重。
				</text>
			</view>

			<view class="children-ready-item">
				<text class="children-title">三、测评道具</text>
				<view class="assess-tool-view">
					<view v-for="(item,index) in imgList" class="assess-tool-item" @click="previewImage(index)" :key="item.id">
						<image class="assess-tool-img" mode="aspectFill" :src="formatImageUrl(item.imgUrl,240,240)"></image>
						<text class="assess-tool-title">{{item.title}}</text>
					</view>
				</view>
			</view>
			<view class="safe-area-view"></view>
		</scroll-view>

		<button v-if="!hasVipMobile()" class="assess-fixed-view" :plain="false" open-type="getPhoneNumber" @getphonenumber="getphonenumber">
			<view style="display: flex;justify-content: center;align-items: center;height: 120rpx;">
				<image src="../../../static/assess-ready.png" class="assess-ready-img"></image>
				<view class="assess-begin">开始测评(获取联系方式)</view>
			</view>
			<view class="safe-area-view"></view>
		</button>
		<view v-else class="assess-fixed-view" @click="beginClick()">
			<view style="display: flex;justify-content: center;align-items: center;height: 120rpx;">
				<image src="../../../static/assess-ready.png" class="assess-ready-img"></image>
				<view class="assess-begin">开始测评</view>
			</view>
			<view class="safe-area-view"></view>
		</view>
		<ws-wx-privacy id="privacy-popup"></ws-wx-privacy>
	</view>
</template>

<script>
	import uniCalendar from '@/components/uni-calendar/uni-calendar.vue'
	import utils from '../../../utils/utils.js'

	export default {
		components: {
			uniCalendar,
		},
		data() {
			return {
				assess: 1,
				childrenId: '',

				imgList: [],
				birthday: '',
				name: '',
				height: '',
				weight: '',
				gender: 0,
				phone: '',
				parentPhone: '',

				startDate: '',
				endDate: '',
				date: '',

				index: 1,
				relationship: ['爸爸', '妈妈', '爷爷', '奶奶', '外公', '外婆', '其他'],

				placeholderStyle: 'font-size:26rpx;color: #CCCCCC;',
				
				color: getApp().globalData.themeColor,
				appId: getApp().globalData.appid,
				
				tips: {
					text: '请选择适合的测评模式(设置中心更改测评模式)',
					color: '#909399',
					fontSize: 30
				},
				list: [{
					text: '向导模式',
					subText: '适合对测评还在学习中的老师'
				}, {
					text: '辅助模式',
					subText: '适合对测评有一定了解的老师'
				}, {
					text: '专家模式',
					subText: '适合对测评非常熟悉的老师'
				}],
				show: false
			}
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			console.log(option);
			// #ifdef MP-WEIXIN
				let ob = wx.getLaunchOptionsSync();
				console.log(ob);
				this.demo = ob.query.demo;
				console.log(this.demo);
			// #endif

			this.assess = parseInt(option.assess);
			this.childrenId = option.childrenId;
			this.month = option.month;
			this.parentPhone = option.phone;
			this.phone = option.phone;
			this.height = option.height;
			this.weight = option.weight;
			this.birthday = option.birthday;

			var now = new Date();
			this.startDate = utils.getDateByMonth(now, -12 * 7).fullDate;
			this.endDate = utils.getDateByMonth(now, -1).fullDate;
			this.date = utils.getDateByMonth(now, -24).fullDate;

			console.log(this.date);
			if (utils.isEmpty(this.month)) {
				this.month = '';
			}
			this.check = false;
			this.getFullEvaluateTools(this.month);

			this.initEvaluateType();
			this.color = getApp().globalData.themeColor;
			
			uni.requirePrivacyAuthorize({
				success: () => {
					console.log('同意');
					// 用户同意授权
					// 继续小程序逻辑
				},
				fail: () => {
					console.log('拒绝');
					uni.navigateBack()
				}, // 用户拒绝授权
				complete: () => {}
			})
		},

		methods: {
			handleDisagree() {
			  // 处理用户不同意隐私协议的逻辑
			},
			handleAgree() {
			  // 处理用户同意隐私协议的逻辑
			},
			bindPickerChange(e) {
				console.log(e.target.value);
				this.index = e.target.value
			},

			formatImageUrl(imgUrl, width, height) {
				return utils.formatImageUrl(imgUrl, width, height)
			},

			radioChange(evt) {
				this.gender = evt.detail.value;
			},

			checkChange(evt) {
				console.log(evt);
				this.check = evt.detail.value;
			},

			open() {
				this.$refs.calendar.open();
			},
			confirm(e) {
				console.log(e);
				var selectDate = new Date(e.fulldate);
				var endDate = new Date(this.endDate);
				console.log(selectDate);
				console.log(endDate);
				if (selectDate <= endDate) {
					this.birthday = e.fulldate;
					this.getFullEvaluateTools('', this.birthday);
					return;
				}
				this.birthday = '';
			},

			beginClick() {

				if (this.isEmpty(this.name) && this.assess === 0) {
					uni.showToast({
						title: '请填写宝宝姓名',
						icon: 'none'
					})
					return;
				}
				if (this.isEmpty(this.birthday) && this.assess === 0) {
					uni.showToast({
						title: '请填写宝宝出生日期',
						icon: 'none'
					})
					return;
				}
				if (this.isEmpty(this.height)) {
					uni.showToast({
						title: '请填写宝宝身高',
						icon: 'none'
					})
					return;
				}
				var height = parseInt(this.height);
				if (height < 40 || height > 150) {
					uni.showToast({
						title: '您输入的身高不在正常范围(40-150cm)',
						icon: 'none'
					})
					return;
				}
				if (this.isEmpty(this.weight)) {
					uni.showToast({
						title: '请填写宝宝体重',
						icon: 'none'
					})
					return;
				}
				var weight = parseInt(this.weight);
				if (weight < 2 || weight > 35) {
					uni.showToast({
						title: '您输入的体重不在正常范围(2-35kg)',
						icon: 'none'
					})
					return;
				}
				if (this.isEmpty(this.gender) && this.assess === 0) {
					uni.showToast({
						title: '请选择宝宝性别',
						icon: 'none'
					})
					return;
				}
				
				if (getApp().globalData.appid != 'wx098b4aa58f613e7b'
					&& getApp().globalData.appid != 'wx785122fc0f5d90fd'){
					if (!utils.checkMobile(this.phone)) {
						uni.showToast({
							title: '请填写正确的联系方式',
							icon: 'none'
						})
						return;
					}
				}

				if (this.assess === 0) {
					///新宝宝
					this.queryChildrenByName();
				} else {
					this.checkEvaluateType(false);
				}
			},
			
			checkEvaluateType(isAdd) {
				if (this.demo === '1') {
					this.addEvaluate(isAdd, 'normal');
					return;
				}
				if (utils.isEmpty(this.evaluateType)) {
					this.isAdd = isAdd;
					this.show = true;
					return;
				}
				this.addEvaluate(isAdd, this.evaluateType);
			},
			
			evaluateTypeClick(index) {
				if (index === 1) {
					this.addEvaluate(this.isAdd, 'pro');
					this.setEvaluateType('pro');
				} else if (index === 2){
					this.addEvaluate(this.isAdd, 'enterprise');
					this.setEvaluateType('enterprise');
				} else {
					this.addEvaluate(this.isAdd, 'normal');
					this.setEvaluateType('normal');
				}
			},
			
			addEvaluate(isAdd, evaluateType) {
				let params = {
					childrenId: this.childrenId,
					height: this.height,
					weight: this.weight,
					birthday: this.birthday,
					guardianPhone: this.phone,
					guardianRelation: this.relationship[this.index],
					skipWarningDiemnsion: !this.check,
					evaluateType: evaluateType,
				}
				if (isAdd) {
					params = {
						birthday: this.birthday,
						childrenName: this.name,
						gender: this.gender,
						height: this.height,
						nickName: this.name,
						weight: this.weight,
						guardianPhone: this.phone,
						guardianRelation: this.relationship[this.index],
						skipWarningDiemnsion: !this.check,
						evaluateType: evaluateType,
					}
				}
				if (evaluateType === 'pro' || evaluateType === 'enterprise') {
					this.assessFullEvaluate(params)
				} else {
					console.log(this.demo);
					if (this.demo === '1') {
						params.demo = 1;
					}
					if (isAdd) {
						this.addEvaluateForNew(params);
					} else {
						this.addEvaluateForChildren(params)
					}
				}
			},

			addEvaluateForChildren(params) {
				console.log(params)
				uni.showLoading({})
				this.$http.post(
						'/eapi/operator/add_evaluate', {}, {
							params: params,
						})
					.then(res => {
						uni.hideLoading();
						console.log(res);
						if (res.code === '000000') {
							uni.redirectTo({
								url: '../assess-content/assess-content?recordId=' + res.data.id
							})
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					})
					.catch(err => {
						uni.hideLoading();
						console.log(err);
					});
			},

			addEvaluateForNew(params) {
				console.log(params)
				uni.showLoading({})
				this.$http.post(
						'/eapi/operator/add_evaluate_for_new', {}, {
							params: params,
						})
					.then(res => {
						uni.hideLoading();
						console.log(res);
						if (res.code === '000000') {
							uni.redirectTo({
								url: '../assess-content/assess-content?recordId=' + res.data.id
							})
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					})
					.catch(err => {
						uni.hideLoading();
						console.log(err);
					});

			},

			//判断字符是否为空的方法
			isEmpty(obj) {
				if (typeof obj == "undefined" || obj == null || obj == "") {
					return true;
				} else {
					return false;
				}
			},

			///道具
			getFullEvaluateTools(month, birthday) {
				uni.showLoading({})
				console.log(month);
				this.$http.request({
						method: 'POST',
						url: '/eapi/operator/full_evaluate_tools',
						params: {
							month: month,
							birthday: birthday,
						}
					})
					.then(res => {
						uni.hideLoading();
						console.log(res);
						if (res.code === '000000') {
							this.imgList = res.data;
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					})
					.catch(err => {
						uni.hideLoading();
						console.log(err);
					});
			},

			///查询是否有草稿没做完
			draftEvaluate() {
				uni.showLoading({});
				var that = this;
				this.$http.request({
					method: 'POST',
					url: '/eapi/operator/draft_evaluate',
					params: {
						'childrenId': this.childrenId,
					}
				}).then(res => {
					console.log(res);
					uni.hideLoading();
					if (res.data != null) {
						var recordId = res.data.id;
						uni.showModal({
							title: '提醒',
							content: '检测到上次测评未完成，是否继续上一次测评',
							confirmColor: this.color,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
									uni.redirectTo({
										url: '../assess-content/assess-content?recordId=' + recordId + '&isDraft=true'
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
									// that.addEvaluate();
								}
							}
						});
					} else {
						// that.addEvaluate();
					}
				}).catch(err => {
					// that.addEvaluate();
					uni.hideLoading();
				})
			},

			///查询同名字宝宝
			queryChildrenByName() {
				uni.showLoading({})
				this.$http.request({
					method: 'POST',
					url: '/eapi/operator/children_by_name',
					params: {
						name: this.name,
					}
				}).then(res => {
					uni.hideLoading();
					if (res.code === '000000') {
						if (res.data.length > 0) {
							this.childrenId = res.data[0].childrenId;
							this.createSameChildren();
							return;
						}
					}
					this.checkEvaluateType(true)
				}).catch(err => {
					uni.hideLoading();
					this.checkEvaluateType(true)
				})
			},

			///询问是否新增宝宝
			createSameChildren() {
				var that = this;
				uni.showModal({
					title: '提示',
					content: '孩子列表已存在' + this.name + '小朋友，是否对该宝宝进行测评?',
					success: function(res) {
						if (res.confirm) {
							that.checkEvaluateType(false);
						} else {
							that.checkEvaluateType(true);
						}
					}
				});
			},
			///预览图片
			previewImage(current) {
				var urls = new Array();
				for (var index in this.imgList) {
					var item = this.imgList[index];
					if (!utils.isEmpty(item.imgUrl)) {
						urls[index] = item.imgUrl;
					}
				}
				uni.previewImage({
					current: current,
					urls: urls,
				})
			},

			onlyNumber(e) {
				this.weight = '';
				var value = e.detail.value;
				console.log(value);
				//得到第一个字符是否为负号
				var t = value.charAt(0);
				//先把非数字的都替换掉，除了数字和. 
				value = value.replace(/[^\d\.]/g, '');
				//必须保证第一个为数字而不是. 
				value = value.replace(/^\./g, '');
				//保证只有出现一个.而没有多个. 
				value = value.replace(/\.{2,}/g, '.');
				//保证.只出现一次，而不能出现两次以上 
				value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
				//如果第一位是负号，则允许添加
				// if (t == '-') {
				// 	value = '-' + value;
				// }
				console.log(value);
				this.weight = value;
			},
			
			onlyNumberHeight(e) {
				this.height = '';
				var value = e.detail.value;
				console.log(value);
				//得到第一个字符是否为负号
				var t = value.charAt(0);
				//先把非数字的都替换掉，除了数字和. 
				value = value.replace(/[^\d\.]/g, '');
				//必须保证第一个为数字而不是. 
				value = value.replace(/^\./g, '');
				//保证只有出现一个.而没有多个. 
				value = value.replace(/\.{2,}/g, '.');
				//保证.只出现一次，而不能出现两次以上 
				value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
				//如果第一位是负号，则允许添加
				// if (t == '-') {
				// 	value = '-' + value;
				// }
				console.log(value);
				this.height = value;
			},
			
			assessFullEvaluate(params) {
				let data = JSON.stringify(params);
				uni.redirectTo({
					url: '../assess-full-evaluate/assess-full-evaluate?data=' + data
				})
			},
			
			initEvaluateType() {
				this.evaluateType = '';
				this.$http.request({
					method: 'GET',
					url: '/eapi/setting/get',
					params: {
						key: 'EvaluateType',
					}
				}).then(res => {
					if (res.code === '000000'){
						this.evaluateType = res.data.value;
					}
					if (this.assess != 0 && this.evaluateType === 'normal') {
						this.draftEvaluate();
					}
				}).catch(error => {
					if (this.assess != 0) {
						this.draftEvaluate();
					}
				})
			},
			
			setEvaluateType(value) {
				this.$http.request({
					method: 'POST',
					url: '/eapi/setting/set',
					params: {
						key: 'EvaluateType',
						value: value,
					}
				}).then(res => {
				}).catch(err => {
				})
			},
			
			hasVipMobile() {
				// console.log(getApp().globalData.user);
				// let vipLevel = getApp().globalData.user.org.vipLevel;
				// if (utils.isEmpty(vipLevel)){
				// 	vipLevel = 0;
				// }
				// if (vipLevel !== 0) {
				// 	if (utils.isEmpty(getApp().globalData.user.mobile)) {
				// 		return false;
				// 	}
				// }
				if (utils.isEmpty(getApp().globalData.user.mobile)) {
					return false;
				}
				return true;
			},
			
			getphonenumber(e){
				console.log(e);
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					this.getPhone(e.detail.encryptedData,e.detail.iv)
				}else{
					this.beginClick();
				}
			},
			
			getPhone(encryptedData,iv){
				uni.showLoading({}) 
				this.$http.request({
					method:'GET',
					url:'/wx/user/'+getApp().globalData.appid+'/wxphone',
					data:{
						appid:getApp().globalData.appid,
						encryptedData:encryptedData,
						iv:iv,
						sessionKey:getApp().globalData.session.sessionKey,
					}
				}).then(res=>{
					console.log(res);
					uni.hideLoading();
					///更新用户信息
					uni.$emit('event_get_user')
					this.beginClick();
				}).catch(err=>{
					console.log(err);
					uni.hideLoading();
					this.beginClick();
				})
			},
		}
	}
</script>

<style lang="scss">
	uni-page-body,
	#app {
		height: 100%;
	}

	.root {
		height: 100%;
		width: 100%;
		background-color: $app-line-color;
	}

	.contet {
		display: flex;
		flex-direction: column;
		background-color: #F7F7F7;
		padding-bottom: 160rpx;
	}

	.children-ready-item {
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
		margin: 20rpx;

		border-radius: 0px 0px 8rpx 8rpx;

		padding-bottom: 20rpx;
	}

	.children-title {
		font-size: 36rpx;
		color: #FFFFFF;
		background: rgba(250, 203, 47, 1);
		opacity: 1;
		border-radius: 8rpx 8rpx 0px 0px;

		padding-top: 20rpx;
		padding-bottom: 20rpx;
		padding-left: 30rpx;
		padding-right: 30rpx;
		@include main-bg();
	}

	.children-info-view {
		display: flex;
		flex-direction: row;
		align-items: center;

		font-size: 30rpx;
		color: #666666;
		margin-top: 26rpx;
		margin-left: 30rpx;
		margin-right: 30rpx;
		width: 650rpx;
		/deep/ .uni-switch-input-checked {
			@include uni-switch-input-checked();
		}
	}

	.children-info-view-left {
		display: flex;
		flex-direction: row;
		flex-grow: 1;
		align-items: center;
	}

	.children-info-view-right {
		display: flex;
		flex-direction: row;
		flex-grow: 1;
		align-items: center;
		justify-content: flex-end;
	}

	.children-info-input {
		width: 200rpx;
		height: 60rpx;
		border: 2rpx solid rgba(153, 153, 153, 1);
		opacity: 1;
		border-radius: 8rpx;
		margin-left: 10rpx;
		padding-left: 10rpx;
		padding-right: 10rpx;
		text-align: right;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.children-sex {
		margin-left: 10rpx;
	}

	.children-sex-radio {
		margin-right: 30rpx;
		/deep/ .uni-radio-input-checked { 
			@include uni-radio-input-checked();
		}
	}

	.ready-hint {
		color: #666666;
		font-size: 24rpx;
		margin-top: 20rpx;
		margin-left: 30rpx;
		margin-right: 30rpx;
		margin-bottom: 20rpx;
		line-height: 50rpx;

		// font-family: "Courier New", Courier, monospace;
		// font-weight:400;
		// line-height:21px;
	}

	.assess-tool-view {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		margin-top: 40rpx;
	}

	.assess-tool-item {
		width: 25%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 32rpx;
	}

	.assess-tool-img {
		width: 120rpx;
		height: 120rpx;
		border-color: #E6E6E6;
		border-width: 1px;
		border-style: solid;
	}

	.assess-tool-title {
		color: #999999;
		font-size: 24rpx;
		margin-top: 6rpx;
	}

	.assess-fixed-view {
		width: 100%;
		position: fixed;
		bottom: 0rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-radius: 0rpx;

		background: rgba(255, 171, 0, 1);
		box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16);
		opacity: 1;

		color: #FFFFFF;
		font-size: 36rpx;
		font-weight: bold;
		@include main-bg();
		border: none;
	}
	
	button::after {
		 border: none;
	}

	.assess-ready-img {
		width: 25rpx;
		height: 42rpx;
	}

	.assess-begin {
		margin-left: 30rpx;
	}

	.chart-title {
		color: #333333;
		font-size: 30rpx;
		margin-top: 40rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
	}

	.chart-hint {
		color: #333333;
		font-size: 30rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}

	.charts {
		width: 100%;
		height: 500upx;
		// background-color: #007AFF;
	}

	.relationship-view {
		width: 174rpx;
		height: 60rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		font-size: 26rpx;
		color: #CCCCCC;
	}

	.relationship-style {
		font-size: 30rpx;
		color: #666666;
	}

	.relationship-dropdown {
		width: 0;
		height: 0;
		border-top: 14rpx solid #707070;
		border-right: 14rpx solid transparent;
		border-bottom: 0rpx solid transparent;
		border-left: 14rpx solid transparent;
		margin-right: 15rpx;
	}
	
</style>
